package com.gzw.scm.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.gzw.scm.DEL.DBManager;
import com.gzw.scm.MyApplication;
import com.gzw.scm.R;
import com.gzw.scm.adapter.ZZXFPAdapter;
import com.gzw.scm.base.BaseActivity;
import com.gzw.scm.bean.DBJGInfo;
import com.gzw.scm.bean.DBSQInfo;
import com.gzw.scm.utils.HttpUtils;
import com.gzw.scm.utils.JsonUtil;
import com.gzw.scm.utils.T;
import com.gzw.scm.utils.UrlUtils;
import com.gzw.scm.view.SwipeRefreshLayout;

import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/5/2.
 */

public class WBZZXActivity extends BaseActivity{
    private Context mContext;
    private RecyclerView mRecyclerView;
    private Toolbar toolbar;
    private Intent intent;
    private Button btn_sure,btn_delete;
    private TextView tv_seleteAll;
    private boolean isCheck = false;
    private DBManager dbManager;
    private List<String> ls_bh,ls_xzbh;
    private ZZXFPAdapter zzxfpAdapter;
    private ProgressDialog mProgressDialog;
    private SwipeRefreshLayout mSwipeLayout;
    private String type;
    private String dataType;
    private DBSQInfo dbsqInfo;
    private List<String> lsbh;
    private Logger log;
    private Integer belongid,bringid;


    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_fpzzx);
    }

    @Override
    protected void initViews() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        mRecyclerView = (RecyclerView) findViewById(R.id.rv_fp);
        btn_sure = (Button)findViewById(R.id.btn_sure);
        btn_delete = (Button)findViewById(R.id.btn_delete);
        tv_seleteAll = (TextView) findViewById(R.id.ic_head1).findViewById(R.id.tv_selectAll);

        //初始化 log
        log=Logger.getLogger(this.getClass());
    }

    @Override
    protected void initData() {
        mContext = this;
        intent = getIntent();
        type=intent.getStringExtra("type");
        dbsqInfo = (DBSQInfo) intent.getExtras().get(
                "dbsqInfo");
        belongid = dbsqInfo.getId();
        bringid = dbsqInfo.getBringid();
        if(type.equals("0")){
            toolbar.setTitle("周转箱调拨接收");
            dataType="dbjs";
        }else {
            toolbar.setTitle("周转箱调拨发出");
            dataType="dbfc";
        }
        setSupportActionBar(toolbar);

        /**
        * 刷新框架
        * */
        mRecyclerView.setHasFixedSize(true);
        //设置布局管理器
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        //设置Item增加、移除动画
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        //添加默认分割线
        mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);

        mSwipeLayout.setColor(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        mSwipeLayout.setMode(SwipeRefreshLayout.Mode.DISABLED);
        mSwipeLayout.setLoadNoFull(false);

        dbManager=new DBManager(mContext);
        ls_bh = new ArrayList<>();
        ls_xzbh = new ArrayList<>();
        lsbh = new ArrayList<>();
        setData();
    }

    @Override
    protected void initEvents() {
        toolbar.setNavigationOnClickListener(new myOnClick());
        btn_sure.setOnClickListener(new myOnClick());
        btn_delete.setOnClickListener(new myOnClick());
        tv_seleteAll.setOnClickListener(new myOnClick());
    }

    class myOnClick implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {
                case R.id.btn_sure:
                    senddata();
                    break;
                case R.id.btn_delete:
                    deleteZzxbh();
                    break;
                case R.id.tv_selectAll:
                    if (ls_bh != null) {
                        if (isCheck == false) {
                            // 遍历list的长度，将MyAdapter中的map值全部设为true
                            for (int i = 0; i < ls_bh.size(); i++) {
                                ZZXFPAdapter.getIsSelected().put(i, true);
                            }
                            zzxfpAdapter.notifyDataSetChanged();
                            //改变状态
                            isCheck = true;
                        } else {
                            // 遍历list的长度，将已选的按钮设为未选
                            for (int i = 0; i < ls_bh.size(); i++) {
                                if (ZZXFPAdapter.getIsSelected().get(i)) {
                                    ZZXFPAdapter.getIsSelected().put(i, false);
                                }
                            }
                            zzxfpAdapter.notifyDataSetChanged();
                            isCheck = false;
                        }
                    }
                    break;
                default:
                    Intent mIntent = new Intent();
                    mIntent.putExtra("result", type);
                    setResult(Integer.parseInt(type), mIntent);

                    finish();
                    break;
            }
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            Intent mIntent = new Intent();
            mIntent.putExtra("result", type);
            setResult(Integer.parseInt(type), mIntent);
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 扫描结果
     * */
    @Override
    protected String scanRelust(String code){
        if(code.contains("该二维码不是周转箱")){
            T.showShort(mContext,"该二维码不是周转箱");
        }else {
            isScan(code);
        }
        return code;
    }

    /**
     * 判断是否已扫
     * */
    private void isScan(String bh){
//        List<String> lsbh=dbManager.selectFPZzxbh(dataType,MyApplication.getUserInfo().getDid());
        List<String> lsbh=dbManager.selectdbZzxbh(belongid,MyApplication.getUserInfo().getDid(),bringid);

        if(type.equals("0")){
            Integer dsmsl = dbsqInfo.getAcceptnumber()-dbsqInfo.getJsnum();
            if (lsbh.size() >= dsmsl) {
                T.showShort(mContext, "扫描数量不能大于待扫描数量");
                return;
            }
        }else if(type.equals("1")){
                Integer fcdsmsl = dbsqInfo.getBringnumber()-dbsqInfo.getAcceptnumber();
                if (lsbh.size() >= fcdsmsl) {
                    T.showShort(mContext, "扫描数量不能大于待扫描数量");
                    return;
            }
        }
//        Boolean isExist = dbManager.IsExistZzxbh(bh,dataType,MyApplication.getUserInfo().getDid());
        Boolean isExist = dbManager.IsExistdbZzxbh(bh,belongid,MyApplication.getUserInfo().getDid(),bringid);

        if(isExist){
            T.showShort(mContext,"该二维码已扫描");
        }else{
//            dbManager.addZzxbh(bh,dataType,MyApplication.getUserInfo().getDid());
            dbManager.addDbZzxbh(bh,belongid,MyApplication.getUserInfo().getDid(),bringid);
            setData();
        }
    }

    /**
     * 列表赋值
     * */
    private void setData(){
        ls_bh.clear();
//        List<String> lsbh=dbManager.selectFPZzxbh(dataType,MyApplication.getUserInfo().getDid());
        List<String> lsbh=dbManager.selectdbZzxbh(belongid,MyApplication.getUserInfo().getDid(),bringid);

        if(lsbh==null){
            return;
        }else {
            ls_bh.addAll(lsbh);
        }
        if(ls_bh==null){
            return;
        }

        zzxfpAdapter = new ZZXFPAdapter(ls_bh);
        mRecyclerView.setAdapter(zzxfpAdapter);

        zzxfpAdapter.setOnRecyclerViewListener(new ZZXFPAdapter.OnRecyclerViewListener() {
            @Override
            public void onItemClick(int position) {
                if(ZZXFPAdapter.getIsSelected().get(position)==true){
                    ZZXFPAdapter.getIsSelected().put(position, false);
                    zzxfpAdapter.notifyDataSetChanged();
                }else{
                    ZZXFPAdapter.getIsSelected().put(position, true);
                    zzxfpAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public boolean onItemLongClick(int position) {
                return false;
            }
        });

    }

    /**
     * 删除周转箱编号
     * */
    private void deleteZzxbh(){
         lsbh.clear();
        for (int i = 0; i < ls_bh.size(); i++) {
            if (zzxfpAdapter.getIsSelected().get(i)) {
                lsbh.add(ls_bh.get(i));
            }
        }
        if(lsbh.size()==0){
            T.showShort(mContext,"请先选择要删除的编号!");
        }else {
            showDeleteInfo(lsbh);
        }
    }

    /**
     * 删除数据是的提示框
     * */
    private void showDeleteInfo(final List<String> ls_bh){
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("确定要删除这"+ls_bh.size()+"个编号吗?");
        builder.setPositiveButton("确定", (dialog, which) ->  {
//                dbManager.deleteFPZzxbh(ls_bh,dataType,MyApplication.getUserInfo().getDid());
            dbManager.deletedbZzxbh(ls_bh,belongid,MyApplication.getUserInfo().getDid(),bringid);
            setData();

        });
        builder.setNegativeButton("取消", (dialog, which) ->{
        });
        builder.show();
    }

    /**
     * 上传数据
     * */
    private void senddata(){

//         List<String> lsbh1=dbManager.selectFPZzxbh(dataType,MyApplication.getUserInfo().getDid());
//            if (lsbh1.size() != dbsqInfo.getBringnumber()) {
//                T.showShort(mContext, "扫描数量不等于申请数量");
//                return;
//            }

        lsbh.clear();
        for (int i = 0; i < ls_bh.size(); i++) {
            if (zzxfpAdapter.getIsSelected().get(i)) {
                lsbh.add(ls_bh.get(i));
            }
        }
        if(lsbh.size()==0){
            T.showShort(mContext,"请先选择要提交的编号");
        }else {
            showSendInfo(lsbh);
        }
    }

    /**
     * 上传数据是的提示框
     * */
    private void showSendInfo(final List<String> ls_bh){
         String show="";
         if(type.equals("0")){
             show="确定要接收这"+ls_bh.size()+"个周转箱吗?";
         }else{
             show="确定要调拨这"+ls_bh.size()+"个周转箱吗?";
         }

        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle(show);
        builder.setPositiveButton("确定", (dialog, which) -> {
                ls_xzbh.clear();
                ls_xzbh.addAll(ls_bh);
                String idStr=new String();
                for (String str:ls_bh){
                    idStr=idStr+str+",";
                }
                idStr = idStr.substring(0, (idStr.length()-1));

                if(type.equals("1")){
                    SendTask sendTask = new SendTask();
                    sendTask.execute(idStr);
                }else if(type.equals("0")){
                    SendDBJSTask sendDBJSTask = new SendDBJSTask();
                    sendDBJSTask.execute(idStr);
                }
        });
        builder.setNegativeButton("取消", (dialog, which) -> {
        });
        builder.show();
    }

    /**
     * 上传调拨发出的数据请求
     * */

    public class SendTask extends AsyncTask<String, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
            mProgressDialog.setCancelable(true);
        }

        protected String doInBackground(String... params) {
            String json ="tboxno="+params[0]+"&did="+MyApplication.getUserInfo().getDid()
                    +"&operator="+MyApplication.getUserInfo().getName()+"&id="+dbsqInfo.getId()
                    +"&brid="+dbsqInfo.getBrid()+"&allocation="+MyApplication.getUserInfo().getDepartment_name();
            return HttpUtils.doPost(UrlUtils.getInstance().getNewJavaUrl("pda_apply.do","confirmApply"), json);
        }

        @Override
        protected void onPostExecute(final String result) {
            mProgressDialog.dismiss();

            try {

            if (result == null || result.length() == 0) {
                showAlertDialog("连接异常");
                return;
            }

            if(result.contains("iden")){
                String info = JsonUtil.getMsg(result,"iden").toString();

                if(info.equals("1")){
                    showAlertDialog("成功发出"+lsbh.size()+"个周转箱");
                    dbManager.deletedbZzxbh(ls_xzbh,belongid,MyApplication.getUserInfo().getDid(),bringid);

                    setData();
                }else if(info.equals("2")){
                    showAlertDialog("调拨发出失败,扫描数量大于调拨数量");
                }else{
                    showAlertDialog("调拨发出失败,箱子"+info+"不符合调拨流程");
                }
            }else if(result.contains("err")){
                String info = JsonUtil.getMsg(result,"err").toString();
                showAlertDialog("调拨发出失败,箱子"+info+"已发出");
            }
            else if(result.contains("系统异常")){
                showAlertDialog("网络异常");
                return;
            }else{
                showAlertDialog("出现异常");
            }
            }catch (Exception e) {
                log.info("confirmApply:"+e.toString()+"/result="+result);
                e.printStackTrace();
                showAlertDialog(e.toString());
            }
        }

    }

    /**
     * 上传调拨接收的数据请求
     * */

    public class SendDBJSTask extends AsyncTask<String, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
            mProgressDialog.setCancelable(true);
        }

        protected String doInBackground(String... params) {
            String json ="tboxno="+params[0]+"&did="+MyApplication.getUserInfo().getDid()
                    +"&operator="+MyApplication.getUserInfo().getName()+"&id="+dbsqInfo.getId()
                    +"&brid="+dbsqInfo.getBrid()+"&allocation="+MyApplication.getUserInfo().getDepartment_name()
                    +"&bringid="+dbsqInfo.getBringid();
            return HttpUtils.doPost(UrlUtils.getInstance().getNewJavaUrl("pda_apply.do","stayReceived"), json);
        }

        @Override
        protected void onPostExecute(final String result) {
            mProgressDialog.dismiss();

            try {
            if (result == null || result.length() == 0) {
                showAlertDialog("连接异常");
                return;
            }
                if(result.contains("系统异常")){
                    showAlertDialog("网络异常");
                    return;
                }
            if(result.contains("iden")){
                String info = JsonUtil.getMsg(result,"iden").toString();

                if(info.equals("1")){
                    showAlertDialog("成功接收"+lsbh.size()+"个周转箱");
                    dbManager.deletedbZzxbh(ls_xzbh,belongid,MyApplication.getUserInfo().getDid(),bringid);
                    setData();
                }else if(info.equals("0")){
                    showAlertDialog("操作失败,请重新操作或进行运维申请");
                }else if(info.equals("2")){
                    showAlertDialog("调拨接收失败,扫描数量大于调拨数量");
                }else if(info.equals("3")){
                    showAlertDialog("调拨接收失败,周转箱不符合调拨流程");
                }else{
                    showAlertDialog("调拨接收失败,箱子"+info+"不符合调拨流程");
                }

            }else if(result.contains("err")){
                String info = JsonUtil.getMsg(result,"err").toString();
                if(info.contains("tboxno")){
                List<DBJGInfo> ls_info = JsonUtil.getPersons(info, new TypeToken<List<DBJGInfo>>() {
                }.getType());
                List<String> ls_no = new ArrayList<>();
                for(DBJGInfo dbjgInfo:ls_info){
                    ls_no.add(dbjgInfo.getTboxno());
                }
                String json = JsonUtil.toJson(ls_no);
                showAlertDialog("调拨接收失败,箱子"+json+"已接收");
                }
            }else {
               showAlertDialog("出现异常");
            }
            }catch (Exception e) {
                log.info("stayReceived:"+e.toString()+"/result="+result);
                e.printStackTrace();
                showAlertDialog(e.toString());
            }
        }

    }
}
